﻿using System;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

namespace ClientApp.UC
{
    public partial class ucCheck : UserControl
    {
        private string name;
        private string value;
        private bool useIPv4 = true;

        public ucCheck(string name, string value)
        {
            InitializeComponent();

            this.name = name;
            this.value = value;

            lblName.Text = name;
            lblUrl.Text = value;

            tmr.Start();
        }

        private void tmr_Tick(object sender, System.EventArgs e)
        {
            // "net.tcp://koisql2:8666/RemotedServices"

            Uri uri = new Uri(value);

            if (uri.Scheme != "net.tcp")
            {
                pnlResult.BackColor = Color.Fuchsia;
                tmr.Stop();
                return;
            }

            IPAddress ipa = Dns.GetHostAddresses(uri.DnsSafeHost)[0];

            try
            {
                TrySocketConnection(useIPv4, ipa, uri.Port);
            }
            catch (System.NotSupportedException ex)
            {
                try
                {
                    TrySocketConnection(false, ipa, uri.Port);
                    useIPv4 = false;
                }
                catch 
                {
                    pnlResult.BackColor = Color.Red;
                }
            }
            catch (Exception ex)
            {
                pnlResult.BackColor = Color.Red;
            }
        }

        private void TrySocketConnection(bool ipv4, IPAddress ipa, int port)
        {
            using (
                Socket sock = new Socket(ipv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6,
                                         SocketType.Stream,
                                         ProtocolType.Tcp))
            {
                sock.Connect(ipa, port);
                if (sock.Connected)
                    pnlResult.BackColor = Color.Green;
                sock.Close();
            }
        }
    }
}
